package com.demo.simpletestapp

import android.app.ActionBar
import android.app.ActivityOptions
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.content.res.Configuration
import android.graphics.PixelFormat
import android.graphics.Rect
import android.os.*
import android.util.Log
import android.view.*
import android.widget.Toast
import androidx.databinding.DataBindingUtil
import com.blankj.utilcode.util.ScreenUtils
import com.demo.simpletestapp.databinding.ActivityMainBinding
import com.demo.simpletestapp.databinding.FloatingBallLayoutBinding
import com.demo.simpletestapp.utils.Utils
import com.demo.simpletestapp.utils.ViewUtils
import com.example.base_lib.BaseActivity

class MainActivity : BaseActivity<ActivityMainBinding>() {


    override fun getLayoutId(): Int {
        return R.layout.activity_main
    }

    override fun onInit() {
        Log.d(TAG, "onInit: ")
        showAppList()
//        binding.btnShow.setOnClickListener {
//            showFloating()
//        }

        showRoundIcon()

        startHomeListener()
        setTitleView()
    }

    private fun setTitleView() {
        val titleContainer: ViewGroup =
            window.decorView.findViewWithTag("cadothy_decor_caption_title_container")
        if (titleContainer != null) { //需要判空，外接屏启动时不会有该tag
            val customTitle: View =
                layoutInflater.inflate(R.layout.custom_caption_title, titleContainer, false)
            //            View customTitle = LayoutInflater.from(this).inflate(R.layout.custom_caption_title,null);
            val layoutParams = WindowManager.LayoutParams(
                ActionBar.LayoutParams.MATCH_PARENT,
                ActionBar.LayoutParams.WRAP_CONTENT
            )
            titleContainer.addView(customTitle, layoutParams)
        }
    }

    private fun startHomeListener() {
        val filter = IntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS)
        registerReceiver(mReceiver, filter)
    }

    override fun onBackPressed() {
        Log.i(TAG, "onBackPressed: ")
        overridePendingTransition(0,0)
        supportFinishAfterTransition() // 取消退出动画
    }

    override fun onUserLeaveHint() {
        Log.i(TAG, "onUserLeaveHint: ")
        overridePendingTransition(0,0)
        supportFinishAfterTransition() // 取消退出动画
    }

    private fun showRoundIcon() {
//        显示圆角图片
        ViewUtils(16).showRoundImage(binding.img)
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        Log.i(TAG, "onKeyDown: ")
        return super.onKeyDown(keyCode, event)
    }

    /**
     * 显示悬浮球
     */
    private fun showFloating() {
        // 创建悬浮球的 View
        val inflateDatabinding = DataBindingUtil.inflate<FloatingBallLayoutBinding>(
            LayoutInflater.from(this),
            R.layout.floating_ball_layout,
            null,
            false
        )
        val overlayView: View = inflateDatabinding.root

        // 将悬浮球添加到 WindowManager
        val params = WindowManager.LayoutParams(
            WindowManager.LayoutParams.WRAP_CONTENT,
            WindowManager.LayoutParams.WRAP_CONTENT,
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY
            } else {
                WindowManager.LayoutParams.TYPE_PHONE
            },
            WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
            PixelFormat.TRANSLUCENT
        )

        // 设置悬浮球的初始位置
        params.gravity = Gravity.TOP or Gravity.START
        params.x = 100
        params.y = 100

        // 添加悬浮球到窗口
        val windowManager = getSystemService(Context.WINDOW_SERVICE) as WindowManager
        windowManager.addView(overlayView, params)

        // 设置悬浮球的触摸逻辑、拖动逻辑等
        // ...

        // 点击悬浮球时的交互逻辑
        inflateDatabinding.btnClose.setOnClickListener {
            Toast.makeText(this, "悬浮球被点击了！", Toast.LENGTH_SHORT).show()
        }
    }

    private fun showAppList() {
        AppsUtil().getInstalledAppsInfo(this)
    }

    override fun onNewIntent(intent: Intent?) {
        super.onNewIntent(intent)
        Log.d(TAG, "onNewIntent: ")
        startMainActivity()
    }

    private fun startMainActivity() {
        Log.d(TAG, "startMainActivity: ")
        val intent = Intent(this, MainActivity::class.java)
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) //必须设置NEW_TASK标记

        val activityOptions: ActivityOptions = Utils.getFreeformWindowModeLaunchOptions()
        if (activityOptions != null) {
            startActivity(intent, activityOptions.toBundle()) //自由窗口模式启动
        } else {
            startActivity(intent) //默认全屏模式启动
        }

        finish()
    }

    override fun onConfigurationChanged(newConfig: Configuration) {
        super.onConfigurationChanged(newConfig)
        Log.d(TAG, "onConfigurationChanged: ")
        Handler(Looper.getMainLooper()).postDelayed({
            startMainActivity()
        },500)
//        Utils.getFreeformWindowModeLaunchOptions().update(this)

    }

    override fun onSaveInstanceState(outState: Bundle, outPersistentState: PersistableBundle) {
        super.onSaveInstanceState(outState, outPersistentState)
        Log.d(TAG, "onSaveInstanceState: 2")
    }

    override fun onSaveInstanceState(outState: Bundle) {
        super.onSaveInstanceState(outState)
        Log.d(TAG, "onSaveInstanceState: 1")
    }

    override fun onRestoreInstanceState(savedInstanceState: Bundle) {
        savedInstanceState.putInt("android.activity.windowingMode",5)
        val right = ScreenUtils.getScreenWidth() - 40
        val bottom = ScreenUtils.getScreenHeight() - 120
        val rect = Rect(40, 0, right, bottom)
        savedInstanceState.putParcelable("android:activity.launchBounds",rect)
        super.onRestoreInstanceState(savedInstanceState)
        Log.d(TAG, "onRestoreInstanceState: 1")
    }

    override fun onRestoreInstanceState(
        savedInstanceState: Bundle?,
        persistentState: PersistableBundle?
    ) {
        super.onRestoreInstanceState(savedInstanceState, persistentState)
        Log.d(TAG, "onRestoreInstanceState: 2")
    }

    override fun onDestroy() {
        if(SimpleApp.mainActivityState) {
            startMainActivity()
        }
        unregisterReceiver(mReceiver)
        super.onDestroy()
    }

    private val mReceiver: BroadcastReceiver = object : BroadcastReceiver() {
        override fun onReceive(context: Context?, intent: Intent) {
            Log.d(TAG, "mReceiver,the intent action = " + intent.action)
            if (Intent.ACTION_CLOSE_SYSTEM_DIALOGS.equals(intent.action)) {
                Log.d(TAG, "reason = " + intent.getStringExtra("reason"))
            }
        }
    }

}